<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', 'menu.wms.inbound.list']" />
    <a-card class="general-card" :title="$t('menu.wms.inbound.list')">

      <!-- 头部区域 -->
      <div class="header">
        <!-- 搜索栏 -->
        <div v-if="showQuery" class="header-query">
          <a-form ref="queryRef" :model="queryParams" layout="inline">
            <a-form-item field="username" hide-label>
              <a-input
                  v-model="queryParams.username"
                  placeholder="输入用户名搜索"
                  allow-clear
                  style="width: 150px"
                  @press-enter="handleQuery"
              />
            </a-form-item>

            <a-form-item field="createdAt" hide-label>
              <range-picker v-model="queryParams.createdAt" />
            </a-form-item>
            <a-form-item hide-label>
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  <template #icon><icon-search /></template>查询
                </a-button>
                <a-button @click="resetQuery">
                  <template #icon><icon-refresh /></template>重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <!-- 操作栏 -->
        <div class="header-operation">
          <a-row>
            <a-col :span="16">
              <a-space>
                <a-button v-permission="['wms:inbound:add']" type="primary" @click="toAdd">
                  <template #icon><icon-plus/></template>新增
                </a-button>

                <a-button
                    v-permission="['wms:inbound:update']"
                    type="primary"
                    status="success"
                    :disabled="single"
                    :title="single ? '请选择一条要修改的数据' : ''"
                    @click="toUpdate(checkedIds[0])"
                >
                  <template #icon><icon-edit /></template>修改
                </a-button>
                <a-button
                    v-permission="['wms:inbound:delete']"
                    type="primary"
                    status="danger"
                    :disabled="multiple"
                    :title="multiple ? '请选择要删除的数据' : ''"
                    @click="handleBatchDelete"
                >
                  <template #icon><icon-delete /></template>删除
                </a-button>
                <a-button
                    v-permission="['wms:inbound:export']"
                    :loading="exportLoading"
                    type="primary"
                    status="warning"
                    @click="handleExport"
                >
                  <template #icon><icon-download /></template>导出
                </a-button>
              </a-space>
            </a-col>
            <a-col :span="12">
              <right-toolbar v-model:show-query="showQuery" @refresh="fetchData"/>
            </a-col>
          </a-row>
        </div>
      </div>


      <a-table
          row-key="id"
          :data="inboundList"
          :loading="loading"
          :pagination="{
              showTotal: true,
              showPageSize: true,
              total: total,
              current: queryParams.page,
            }"
          :bordered="false"
          :size="size"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
          @selection-change="handleSelectionChange"
          :row-selection="{
              type: 'checkbox',
              showCheckedAll: true,
              onlyCurrent: false,
            }"
      >

        <template #columns>
          <a-table-column title="ID" data-index="id" :width="85" />

          <a-table-column title="仓库ID" :width="150">
            <template #cell="{ record }">
              <a-link @click="toDetail(record.warehouseId)">{{
                  record.warehouseId
                }}</a-link>
            </template>
          </a-table-column>

          <a-table-column title="货架ID" data-index="warehouseShelfId" :width="120" />
          <a-table-column title="用户账号" data-index="memberId" :width="120" />
          <a-table-column title="收货人" data-index="receiveName" :width="120" />
          <a-table-column title="收货地址" data-index="receiveAddress" :width="120" />
          <a-table-column title="收货电话" data-index="receivePhone" :width="120" />
          <a-table-column title="快递单号" data-index="expressNo" :width="120" />
          <a-table-column title="快递公司编码" data-index="expressCode" :width="120" />
          <a-table-column title="运费" data-index="expressFreight" :width="120" />

          <a-table-column
              title="操作"
              align="center"
              fixed="right"
              :width="80"
          >
            <template #cell="{ record }">
              <a-button
                  v-permission="['wms:inbound:update']"
                  type="text"
                  size="small"
                  title="修改"
                  @click="toUpdate(record.id)"
              >
                <template #icon><icon-edit /></template>
              </a-button>
              <a-popconfirm
                  content="确定删除吗？"
                  type="warning"
                  @ok="handleDelete([record.id])"
              >
                <a-button
                    v-permission="['wms:inbound:delete']"
                    type="text"
                    size="small"
                    title="删除"
                    :disabled="record.disabled"
                >
                  <template #icon><icon-delete /></template>
                </a-button>
              </a-popconfirm>

            </template>
          </a-table-column>
        </template>


      </a-table>
    </a-card>



  </div>



</template>

<script lang="ts" setup>
  import {getCurrentInstance, reactive, ref, toRefs} from 'vue';
  import {useI18n} from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {PolicyRecord} from '@/api/list';
  import {
    addInbound,
    getInbound,
    updateInbound,
    deleteInbound,
    InboundSaveCommand,
    InboundParam,
    InboundResponse,
    pageInbound
  } from "@/api/wms/inbound";
  import checkPermission from '@/utils/check-permission';
  import {DictResponseState} from "@/store/modules/dict/types";
  import {AxiosResponse} from "axios";
  import {HttpResponse} from "@/api/interceptor";

  const showQuery = ref(true);

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const { proxy } = getCurrentInstance() as any;
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);

  const size = ref<SizeProps>('medium');
  const checkedIds = ref<Array<number>>([]);
  const title = ref('');
  const single = ref(true);
  const multiple = ref(true);

  const data = reactive({
    queryParams: {
      username: undefined,
      status: 1,
      createdAt: undefined,
      page: 1,
      size: 10,
      sort: ['createdAt,desc'],
    },
    inboundAddForm: {} as InboundSaveCommand,
    rules: {
      username: [{ required: true, message: '请输入管理员用户名' }],
      password: [{ required: true, message: '请输入管理员密码' }],
      roleIds: [{ required: true, message: '请选择所属角色' }],
    },

  });
  const { queryParams,inboundAddForm,rules } = toRefs(data);

  const inboundList = ref<InboundResponse[]>([]);
  const total = ref(0);

  const inbound = ref<InboundResponse>({
    id: undefined,
      warehouseId: undefined,
      warehouseShelfId: undefined,
      memberId: undefined,
      orderId: undefined,
      orderNo: '',
      inboundReturnOrderStatus: undefined,
      receiveName: '',
      receiveAddress: '',
      receivePhone: '',
      freight: undefined,
      payType: undefined,
      totalAmount: undefined,
      freightAmount: undefined,
      promotionAmount: undefined,
      pointAmount: undefined,
      couponAmount: undefined,
      adminDiscountAmount: undefined,
      payAmount: undefined,
      orderComment: '',
      sellInboundOrderStatus: undefined,
          
      returnReason: undefined,
      returnComment: '',
      arrivalTime: '',

    createdBy: '',
    updatedBy: '',
    createdAt: '',
    updatedAt: '',
  });

  const fetchData = (params: InboundParam = {...queryParams.value}) => {
    setLoading(true);
    pageInbound(params).then(res => {
      inboundList.value = res.data.list;
      total.value = Number(res.data.total);
    }).finally(() => {
      setLoading(false);
    });

  };

  fetchData();
  const reset = () => {
    inboundAddForm.value = {
      id: undefined,
      warehouseId: undefined,
      warehouseShelfId: undefined,
      memberId: undefined,
      orderId: undefined,
      orderNo: '',
      inboundReturnOrderStatus: undefined,
      receiveName: '',
      receiveAddress: '',
      receivePhone: '',
      freight: undefined,
      payType: undefined,
      totalAmount: undefined,
      freightAmount: undefined,
      promotionAmount: undefined,
      pointAmount: undefined,
      couponAmount: undefined,
      adminDiscountAmount: undefined,
      payAmount: undefined,
      orderComment: '',
      sellInboundOrderStatus: undefined,
          
      returnReason: undefined,
      returnComment: '',
      arrivalTime: '',
    };
    proxy.$refs.formRef?.reserFields();
  };

  const visible = ref(false);
  const toAdd = () => {
    reset();
    title.value = '新增出库单';
    visible.value = true;
  };

  const roleLoading = ref(false);
  const roleOptions = ref<DictResponseState[]>([]);


  const toUpdate = (id: number) => {
    reset();
    getInbound(id).then((res) => {
      inboundAddForm.value = res.data as unknown as InboundSaveCommand;
      title.value = '修改出库订单';
      visible.value = true;
    });
  };

  const handleQuery = () => {
    console.log("handleQuery", queryParams);
    fetchData();
  };

  const resetQuery = () => {
    proxy.$refs.queryRef.resetFields();
    handleQuery();
  };

  const handlePageChange = (current: number) => {
    queryParams.value.page = current;
    fetchData();
  };

  const handlePageSizeChange = (pageSize: number) => {
    queryParams.value.size = pageSize;
    fetchData();
  };

  const handleSelectionChange = (rowKeys: Array<any>) => {
    checkedIds.value = rowKeys;
    single.value = rowKeys.length !== 1;
    multiple.value = !rowKeys.length;
  };


  const handleCancel = () => {
    visible.value = false;
    inboundRoleVisible.value =false;
    proxy.$refs.formRef?.resetFields();
    proxy.$refs.userRoleFormRef?.resetFields();
  };

  const handleOk = () => {
    proxy.$refs.formRef.validate((valid: any) => {
      if (!valid) {
        if (inboundAddForm.value.id !== undefined) {
          updateInbound(inboundAddForm.value).then((res:any) => {
            handleCancel();
            fetchData();
            proxy.$message.success(res.message);
          });
        } else {
          addInbound(inboundAddForm.value).then((res:any) => {
            handleCancel();
            fetchData();
            proxy.$message.success(res.message);
          });
        }
      }
    });
  };

  const handleDelete = (ids: Array<number>) => {
    deleteInbound(ids).then((res:any) => {
      proxy.$message.success(res.message);
      fetchData();
    });
  };


  const inboundRoleVisible = ref(false);

  const detailLoading = ref(false);
  const detailVisible = ref(false);
  const toDetail = async (id: number) => {
    if (detailLoading.value) return;
    detailLoading.value = true;
    detailVisible.value = true;
    getInbound(id)
        .then((res) => {
          inbound.value = res.data;
        })
        .finally(() => {
          detailLoading.value = false;
        });
  };

  const handleDetailCancel = () => {
    detailVisible.value = false;
  };

  const handleBatchDelete = () => {
    if(checkedIds.value.length === 0) {
      proxy.$message.info('没有选中数据');
    }else {
      proxy.$modal.warning({
        title: '警告',
        titleAlign: "start",
        content: '确定删除吗？',
        hideCancel: false,
        onOk: () => {
          handleDelete(checkedIds.value);
        }
      });
    }
  }

  const exportLoading = ref(false);
  const handleExport = () => {
    if(exportLoading.value) return;

    exportLoading.value = true;
    proxy
        .download('/inbound/wms/inbound/export', { ...queryParams.value }, '用户数据')
        .finally(() => {
          exportLoading.value = false;
        });

  }


</script>

<script lang="ts">
export default {
  name: 'SearchTable',
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.header {
  padding-bottom: 10px;
}
</style>
